import { Toast } from 'antd-mobile'
import md5 from 'md5'
import { createAction, NavigationActions } from '../utils'
import * as authService from '../services/auth'
import * as storageService from '../services/asyncStorage'
import * as StringUtils from '../utils/StringUtils'
import * as Libs from '../utils/Libs'

export default {
  namespace: 'app',
  state: {
    userName: '',
    userPassword: '',
  },
  reducers: {
    modifyState(state, { payload }) {
      return { ...state, ...payload}
    }
  },
  effects: {
    *loadStorage(action, { call, put }) {
      const getResp = yield call(storageService.get, "userinfo")
      console.log('userinfo resp: ', getResp)
      if(getResp.status === 200) {
        const data = getResp.data
        yield put(createAction("modifyState")({
          userName: data.userName,
          userPassword: data.userPassword
        }))
      }
    },
    *login({ payload }, { call, put, select }) {
      const params = yield select(state => state.app)
      if (StringUtils.isBlank(params.userName)) {
        Toast.info('请输入用户名', 1)
        return false
      }
      if (StringUtils.isBlank(params.userPassword)) {
        Toast.info("请输入密码", 1)
        return false
      }
      const resp = yield call(authService.login, {
        userName: params.userName,
        passWord: md5(params.userPassword).toUpperCase()
      })
      if (resp.resultCode !== 200) {
        Toast.info(resp.msg, 1)
        return false
      }
      const sysUserModel = resp.data || {}
      const storageD = sysUserModel.sysUserModel
      storageD.userName = params.userName
      storageD.userPassword = params.userPassword
      yield call(storageService.put, "userinfo", storageD)
      Libs.setOnlyUserInfo(storageD)
      Libs.setToken(sysUserModel.tokens)
      yield put(
        NavigationActions.reset({
          index: 0,
          actions: [NavigationActions.navigate({routeName: 'Main'})],
        })
      )
    },
    subscriptions: {
    },
  }
}
